package com.shkco.filter;

import com.alibaba.fastjson.JSONObject;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        // 获取请求地址
        String requestURI = RequestContext.getCurrentContext().getRequest().getRequestURI();
        // 判断请求路径是否以login/register结尾，包含就不执行登录业务校验，所以返回false
        if (requestURI.endsWith("login") || requestURI.endsWith("register")){
            return false;
        }
        // 如果不包含那么说明用户访问的资源是受保护的资源，那么需要执行登录校验
        return true;
    }

    @SneakyThrows
    @Override
    public Object run() throws ZuulException {
        // 获取请求的token
        String token = RequestContext.getCurrentContext().getRequest().getHeader("token");
        // 获取响应头
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        response.setContentType("application/json;charset=utf-8");
        // 判断token是否为空
        if (StringUtils.isEmpty(token)){
            // 如果为空设置响应内容，提示用户
            PrintWriter writer = response.getWriter();
            HashMap<String, Object> map = new HashMap<>();
            map.put("success", false);
            map.put("msg","请登录！");
            map.put("obj","noLogin");
            String jsonString = JSONObject.toJSONString(map);
            writer.write(jsonString);
            RequestContext.getCurrentContext().setSendZuulResponse(false);
        }
        return null;
    }
}
